 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package cn.shun.config;

 import cn.shun.entity.IdWorker;
 import org.apache.ibatis.executor.Executor;
 import org.apache.ibatis.mapping.MappedStatement;
 import org.apache.ibatis.plugin.Interceptor;
 import org.apache.ibatis.plugin.Intercepts;
 import org.apache.ibatis.plugin.Invocation;
 import org.apache.ibatis.plugin.Signature;
 import org.springframework.beans.factory.annotation.Autowired;

 import java.lang.reflect.Method;
 import java.util.HashMap;
 import java.util.Map;

 /**
  * 此拦截器会自动调动IdWorker 为参数设置id map.put("id",xxx) | xxx.setId(xxx)
  * <p>Project: MyBatis2023 - SnowFlakeInterceptor
  * <p>Powered by yishun On 2023-01-30 21:47:39
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */
 //mybatis雪花算法插件
 @Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
 public class SnowFlakeInterceptor implements Interceptor {
     @Autowired
     private IdWorker idw;
     @Override
     public Object intercept(Invocation invocation) throws Throwable {
         MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
         if ("INSERT".equals(ms.getSqlCommandType().toString())) {
             Object obj = invocation.getArgs()[1];
             if(obj instanceof HashMap){
                 Map<String,Object> map= (Map<String, Object>) obj;
                 map.put("id",idw.nextId());
             }else {
                 Method m = obj.getClass().getMethod("setId", Long.class);
                 m.invoke(obj,idw.nextId());
             }
             System.out.println(obj);
         }
//         System.out.println(invocation.getTarget().getClass().getName());
//         System.out.println(invocation.getMethod().getName());
//         System.out.println(invocation.getMethod().getReturnType().getName());
//         System.out.println(List.of(invocation.getArgs()));
         //MappedStatement ms= (MappedStatement) invocation.getArgs()[0];
         //System.out.println(ms.getId());//cn.yishun.mapper.StudentMapper.xxx
         //System.out.println(ms.getSqlCommandType());//INSERT
         return invocation.proceed();
     }
 }
